from flask import Flask, Response, request, Blueprint
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from sqlalchemy import and_

from app.model.CalculationModel import CalcuResult
from app.service.OpponentCharactersService import OpponentCharactersService
from app.service.OpponentCharactersService_Pandas import OpponentCharactersServicePandas
from app.common.commonMessage import CommonMassages
from app.config.db import DBUtils

import json
app = Flask(__name__)
# 创建蓝图
opponent_characters_bp = Blueprint('opponent_character', __name__,url_prefix='/kshx')

opponentCharactersService = OpponentCharactersService()
opponentCharactersServicePandas = OpponentCharactersServicePandas()

# 获取session
db_utils = DBUtils()
session = db_utils.get_session()

@opponent_characters_bp.route('/opponentCharacters', methods=['GET'])
# @jwt_required()
def get_opponent_characters():
    companyName = request.args.get("companyName", type=str)
    company_type = request.args.get("company_type", type=int)
    start_date = request.args.get("start_date", type=str)
    end_date = request.args.get("end_date", type=str)
    if int(company_type) in [2,3]:
        result = session.query(CalcuResult.JSONDATA).filter(
            and_(
                CalcuResult.GSMC == companyName,
                CalcuResult.TYPE == 'ot',
                CalcuResult.JYND == start_date[:4]
            )
        ).scalar()
        data = json.loads(result)
    else:
        data1 = opponentCharactersServicePandas.select_dstz_data(session,companyName, company_type, start_date, end_date)
        data2 = opponentCharactersServicePandas.select_dsgm_cydw_data(session,companyName, company_type, start_date, end_date)
        data3 = opponentCharactersServicePandas.select_dyfb_data(session,companyName, company_type, start_date, end_date)
        data4 = opponentCharactersServicePandas.select_hyfb_data(session,companyName, company_type, start_date, end_date)
        data = {
            'max_info': data1, # 对手特征
            'dsgm_cydw': data2, # 对手规模情况&成员单位分布
            'dyfb': data3, # 对手地域分布
            'hyfb': data4 # 对手行业分布
        }
    if data is not None:
        respResult = {
            "code": 200,
            "data": data,
            "message": CommonMassages.CCD_SELECT_SUCCESS.value
        }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_SELECT_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False)
    return Response(resp_data, content_type='application/json')